import { wechatShare, defaultShareConfig } from '@/utils/wechatShare'

let initialized = false

/**
 * 初始化全局微信分享配置
 * - 在 H5 微信环境下自动初始化 JSSDK
 * - 设置默认分享（标题/描述/链接/图片）
 * - 暴露 window.setGlobalShare 以便页面级覆盖
 * - 路由变化时自动刷新分享链接
 */
export function setupWechatShare(): void {
  if (initialized) return
  initialized = true

  const init = async () => {
    try {
      // 使用当前域名作为签名 URL（后端需按域名白名单配置）
      const signUrl = typeof window !== 'undefined' ? window.location.origin : undefined
      await wechatShare.initWechatSDK(signUrl)

      // 默认分享配置（链接使用当前地址）
      wechatShare.setShareConfig({
        title: defaultShareConfig.title,
        desc: defaultShareConfig.desc,
        link: typeof window !== 'undefined' ? window.location.href : defaultShareConfig.link,
        imgUrl: defaultShareConfig.imgUrl,
      })
    } catch (error) {
      console.error('初始化全局微信分享失败:', error)
    }
  }

  init()

  // 暴露全局覆盖方法：页面可按需调用覆盖分享内容
  ;(window as any).setGlobalShare = (cfg: Partial<typeof defaultShareConfig>) => {
    try {
      wechatShare.setShareConfig({
        title: cfg.title ?? defaultShareConfig.title,
        desc: cfg.desc ?? defaultShareConfig.desc,
        link: cfg.link ?? (typeof window !== 'undefined' ? window.location.href : defaultShareConfig.link),
        imgUrl: cfg.imgUrl ?? defaultShareConfig.imgUrl,
      })
    } catch (e) {
      console.error('设置全局分享失败:', e)
    }
  }

  // 路由变化时自动刷新分享链接
  const refreshShare = () => {
    try {
      wechatShare.setShareConfig({
        title: defaultShareConfig.title,
        desc: defaultShareConfig.desc,
        link: typeof window !== 'undefined' ? window.location.href : defaultShareConfig.link,
        imgUrl: defaultShareConfig.imgUrl,
      })
    } catch {}
  }

  if (typeof window !== 'undefined') {
    window.addEventListener('popstate', refreshShare)
    const rawPushState = history.pushState
    try {
      history.pushState = function (...args: any[]) {
        const ret = rawPushState.apply(this, args as any)
        setTimeout(refreshShare, 0)
        return ret as any
      } as any
    } catch {}
  }
}


